@using System.Text.Json
@model VotingSystem.ViewModels.VoteViewModel

@{
    ViewData["Title"] = "投票详情";
    // 获取用户已投票的选项Id集合
    var myOptionIds = Model.MyVoteRecords?.Select(r => r.OptionTitle).ToList() ?? new List<string>();
}

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h4 class="card-title mb-0">@Model.Title</h4>
                        @if (Model.IsCreator)
                        {
                            <div class="dropdown">
                                <button class="btn btn-outline-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="fas fa-ellipsis-v"></i>
                                </button>
                                <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                    <li>
                                        <a class="dropdown-item" href="#" onclick="copyShareLink(); return false;">
                                            <i class="fas fa-share-alt me-2"></i>复制分享链接
                                        </a>
                                    </li>
                                    @if (Model.IsActive)
                                    {
                                        <li>
                                            <form asp-action="Close" asp-route-id="@Model.Id" method="post" style="display: inline;">
                                                @Html.AntiForgeryToken()
                                                <button type="submit" class="dropdown-item" onclick="return confirm('确定要结束这个投票吗？')">
                                                    <i class="fas fa-stop-circle me-2"></i>结束投票
                                                </button>
                                            </form>
                                        </li>
                                    }
                                    <li>
                                        <form asp-action="Delete" asp-route-id="@Model.Id" method="post" style="display: inline;">
                                            @Html.AntiForgeryToken()
                                            <button type="submit" class="dropdown-item text-danger" onclick="return confirm('确定要删除这个投票吗？此操作不可恢复！')">
                                                <i class="fas fa-trash-alt me-2"></i>删除投票
                                            </button>
                                        </form>
                                    </li>
                                </ul>
                            </div>
                        }
                    </div>
                    <p class="text-muted mb-3">@Model.Description</p>
                    <div class="mb-2 small text-secondary">
                        <span class="me-3"><i class="fas fa-clock"></i> 创建：@Model.CreateTime.ToString("yyyy-MM-dd HH:mm")</span>
                        <span class="me-3"><i class="fas fa-hourglass-end"></i> 截止：@Model.EndTime.ToString("yyyy-MM-dd HH:mm")</span>
                        <span class="me-3"><i class="fas fa-users"></i> 总票数：@Model.TotalVotes</span>
                        <span class="me-3"><i class="fas fa-user-secret"></i> @(Model.IsPublic ? "公开" : "私密")</span>
                        <span class="me-3"><i class="fas fa-user"></i> @(Model.IsAnonymous ? "匿名" : "实名")</span>
                        <span class="me-3"><i class="fas fa-info-circle"></i> 状态：<span class="badge @(Model.IsActive ? "bg-success" : "bg-secondary")">@(Model.IsActive ? "进行中" : "已结束")</span></span>
                    </div>
                </div>
            </div>

            <!-- 查看结果按钮 -->
            <div class="card mb-4">
                <div class="card-body text-center">
                    <a href="@Url.Action("Results", "Vote", new { id = Model.Id })" class="btn btn-primary">
                        <i class="fas fa-chart-bar"></i> 查看投票结果
                    </a>
                </div>
            </div>

            <!-- 参与者列表，仅实名投票显示 -->
            @if (!Model.IsAnonymous && Model.Participants?.Any() == true)
            {
                // 对参与者进行分组，确保每个用户只显示一次
                var uniqueParticipants = Model.Participants
                    .GroupBy(p => p.Name)
                    .Select(g => g.OrderByDescending(p => p.VoteTime).First())
                    .ToList();
                
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>参与者列表（@uniqueParticipants.Count）</span>
                        <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#participantsList">
                            <i class="fas fa-chevron-down"></i>
                        </button>
                    </div>
                    <div class="collapse show" id="participantsList">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>参与者</th>
                                            <th>投票时间</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach (var participant in uniqueParticipants)
                                        {
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <i class="fas fa-user-circle me-2 text-primary"></i>
                                                        <span>@participant.Name</span>
                                                    </div>
                                                </td>
                                                <td>@participant.VoteTime.ToString("yyyy-MM-dd HH:mm:ss")</td>
                                            </tr>
                                        }
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            }

            @if (Model.NeedLogin)
            {
                <div class="modal show" tabindex="-1" style="display:block; background:rgba(0,0,0,0.5);">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">需要登录</h5>
                            </div>
                            <div class="modal-body">
                                <p>该投票需要登录后才能参与，请先登录。</p>
                            </div>
                            <div class="modal-footer">
                                <a href="@Url.Action("Login", "Account", new { returnUrl = Url.Action("Details", new { id = Model.Id }) })" class="btn btn-primary">去登录</a>
                                <button class="btn btn-secondary" onclick="window.history.back();">返回</button>
                            </div>
                        </div>
                    </div>
                </div>
                <style>body { overflow: hidden; }</style>
            }
            else
            {
                @* 只允许投票，不显示结果和个人投票记录 *@
                @if (Model.CanVote || (Model.HasVoted && Model.AllowModify))
                {
                    <div class="card mb-4">
                        <div class="card-header">参与投票</div>
                        <div class="card-body">
                            @if (Model.Type == VotingSystem.Models.VoteType.Multiple)
                            {
                                <div class="alert alert-info mb-2">最多可选 @Model.MaxVotesPerUser 项</div>
                            }
                            @if (Model.HasVoted && Model.AllowModify)
                            {
                                <div class="alert alert-info mb-2">你可以修改你的投票，修改后将覆盖原有结果。</div>
                            }
                            @if (!Model.IsActive)
                            {
                                <div class="alert alert-warning mb-2">投票已结束，无法再提交或修改。</div>
                            }
                            <form asp-action="Vote" asp-route-id="@Model.Id" method="post" id="voteForm">
                                @if (!string.IsNullOrEmpty(Model.Password))
                                {
                                    <div class="mb-3">
                                        <label class="form-label">投票密码</label>
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="fas fa-key"></i></span>
                                            <input type="password" name="password" class="form-control" required @(Model.IsActive ? "" : "disabled") />
                                        </div>
                                    </div>
                                }
                                <div class="options-container">
                                    @foreach (var option in Model.Options)
                                    {
                                        <div class="option-item card mb-3">
                                            <div class="card-body">
                                                @if (!string.IsNullOrEmpty(option.ImageUrl))
                                                {
                                                    <img src="@option.ImageUrl" class="img-fluid rounded mb-3" alt="@option.Title" />
                                                }
                                                <div class="d-flex align-items-center">
                                                    @if (Model.Type == VotingSystem.Models.VoteType.Single)
                                                    {
                                                        <input type="radio" name="selectedOptions" value="@option.Id" class="form-check-input me-2" required @(myOptionIds.Contains(option.Title) ? "checked" : "") @(Model.IsActive ? "" : "disabled") />
                                                    }
                                                    else if (Model.Type == VotingSystem.Models.VoteType.Multiple)
                                                    {
                                                        <input type="checkbox" name="selectedOptions" value="@option.Id" class="form-check-input me-2 multi-checkbox" @(myOptionIds.Contains(option.Title) ? "checked" : "") @(Model.IsActive ? "" : "disabled") />
                                                    }
                                                    else if (Model.Type == VotingSystem.Models.VoteType.Rating)
                                                    {
                                                        <div class="rating-input">
                                                            <input type="number" name="ratings[@option.Id]" class="form-control" min="1" max="@option.MaxRating" required @(Model.IsActive ? "" : "disabled") />
                                                            <small class="text-muted">@option.RatingDescription</small>
                                                        </div>
                                                    }
                                                    <div class="flex-grow-1">
                                                        <h5 class="mb-1">@option.Title</h5>
                                                        @if (!string.IsNullOrEmpty(option.Description))
                                                        {
                                                            <p class="text-muted mb-0">@option.Description</p>
                                                        }
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    }
                                </div>
                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary" @(Model.IsActive ? "" : "disabled")>
                                        <i class="fas fa-vote-yea"></i> @(Model.HasVoted && Model.AllowModify ? "修改投票" : "提交投票")
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                }
                else if (Model.HasVoted)
                {
                    <div class="alert alert-success mb-4">
                        你已完成投票。
                    </div>
                }

                @if (Model.MyVoteRecords != null && Model.MyVoteRecords.Any())
                {
                    <div class="card mb-4">
                        <div class="card-header">我的投票记录</div>
                        <div class="card-body">
                            <ul class="list-group list-group-flush">
                                @foreach (var record in Model.MyVoteRecords)
                                {
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <span>@record.OptionTitle @(record.Rating.HasValue ? $" 评分: {record.Rating} 分" : "")</span>
                                        <span class="text-muted small">@record.VoteTime.ToString("yyyy-MM-dd HH:mm:ss")</span>
                                    </li>
                                }
                            </ul>
                        </div>
                    </div>
                }

                <div class="d-flex gap-2 mb-4">
                    <button onclick="history.back()" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left"></i> 返回上一页
                    </button>
                    @if (User.Identity?.IsAuthenticated == true && Model.CreatorName == User.Identity?.Name)
                    {
                        if (Model.IsActive)
                        {
                            <form asp-action="Close" method="post" class="d-inline">
                                <input type="hidden" name="id" value="@Model.Id" />
                                <button type="submit" class="btn btn-danger">
                                    <i class="fas fa-stop-circle"></i> 结束投票
                                </button>
                            </form>
                        }
                        <form asp-action="Delete" method="post" class="d-inline" onsubmit="return confirm('确定要删除此投票吗？此操作不可恢复！');">
                            <input type="hidden" name="id" value="@Model.Id" />
                            <button type="submit" class="btn btn-outline-danger">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </form>
                    }
                </div>
            }
        }
    </div>
</div>

@section Styles {
    <style>
        .progress-bar {
            font-size: 1rem;
        }
        .img-thumbnail {
            max-height: 120px;
        }
    </style>
}

@section Scripts {
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        // Chart.js 渲染
        const labels = @Html.Raw(JsonSerializer.Serialize(Model.Options.Select(o => o.Title)));
        const data = @Html.Raw(JsonSerializer.Serialize(Model.Options.Select(o => o.Votes)));
        const ctx = document.getElementById('voteChart');
        if (ctx) {
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '票数',
                        data: data,
                        backgroundColor: 'rgba(54, 162, 235, 0.5)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { display: false }
                    },
                    scales: {
                        y: { beginAtZero: true, precision:0 }
                    }
                }
            });
        }
        // 导出CSV
        function exportCSV() {
            let csv = '选项,票数\n';
            @foreach (var o in Model.Options)
            {
                <text>csv += '@o.Title,@o.Votes\n';</text>
            }
            let blob = new Blob([csv], {type: 'text/csv'});
            let link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = '投票结果.csv';
            link.click();
        }
        $(function() {
            var max = @Model.MaxVotesPerUser;
            if (@Model.Type == @((int)VotingSystem.Models.VoteType.Multiple)) {
                $(document).on('change', '.multi-checkbox', function() {
                    var checked = $('.multi-checkbox:checked');
                    if (checked.length > max) {
                        this.checked = false;
                        alert('最多只能选择 ' + max + ' 项');
                    }
                });
            }
        });
    </script>
    <script>
        $(document).ready(function() {
            // 分享按钮点击事件
            $('.share-btn').click(function() {
                var id = $(this).data('id');
                var title = $(this).data('title');
                var shareUrl = window.location.origin + '/Vote/Vote/' + id;
                
                $('#shareUrl').val(shareUrl);
                $('#shareModal').modal('show');
            });

            // 复制链接按钮点击事件
            $('#copyBtn').click(function() {
                var shareUrl = $('#shareUrl');
                shareUrl.select();
                document.execCommand('copy');
                
                // 显示复制成功提示
                var btn = $(this);
                var originalText = btn.html();
                btn.html('<i class="fas fa-check"></i>');
                setTimeout(function() {
                    btn.html(originalText);
                }, 2000);
            });
        });
    </script>
    <script>
        function copyShareLink() {
            var shareLink = window.location.origin + '/Vote/Details/@Model.Id?token=@Model.AccessToken';
            navigator.clipboard.writeText(shareLink).then(function() {
                alert('分享链接已复制到剪贴板！');
            }).catch(function(err) {
                alert('复制失败，请手动复制链接：' + shareLink);
            });
        }
    </script>
} 